<?php
/**
 * Created by PhpStorm.
 * User: jsb
 * Date: 2018/8/11
 * Time: 11:52
 */

namespace app\api\service;

use app\api\model\Product;
use app\lib\enum\OrderStatusEnum;
use think\Loader;
use app\api\model\Order as OrderModel;
use app\api\service\order as orderService;

Loader::import('WxPay.WxPay', EXTEND_PATH, '.Notify.php');
class WxNotify extends \WxPayNotify
{
    public function NotifyProcess($objData, $config, &$msg)
    {
        if($objData['result_code'] = 'SUCCESS')
        {
            $orderNo = $objData['out_trade_no'];
            try
            {
                 //把整个过程用事务锁起来, 防止微信多次发送请求时的重复减库存
                 Db::startTrans();
                 $order = OrderModel::where(['order_no' => $orderNo]) -> find();
                 if($order['status'] == 1)
                 {
                     $orderService = new OrderService();
                     $stockStatus = $orderService -> checkOrderStock($order -> id);
                     if($stockStatus['pass'])
                     {
                         $this -> updateOrderStatus($order -> id, true);
                         $this -> reduceStock($stockStatus);
                     }
                     else
                     {
                         $this -> updateOrderStatus($order -> id,  false);
                     }
                }
                Db::commit();
                return true;
            }
            catch(\Exception $ex)
            {
                Log::error($ex);
                return false;
            }
        }
        else
        {
            return true;
        }
    }
    //更新status状态信息
    private function updateOrderStatus($orderId, $success)
    {
        $status = $success ? OrderStatusEnum::PAID : OrderStatusEnum::PAID_BUT_OUT_OF;
        OrderModel::where(['order_id' => $orderId]) -> upadte(['status' => $status]);
    }
    //减少库存量
    private function reduceStock($stockStatus)
    {
        foreach ($stockStatus['pStatusArray'] as $signalPStatus)
        {
            $count = $signalPStatus['count'];
            Product::where(['id' => $signalPStatus['id']]) -> setDec('stock', $count);
        }
    }
}